# -*- coding: utf-8 -*-

import Image
import hashlib

from datetime import datetime

from mongoengine.django.storage import GridFSStorage 

from django.utils.encoding import smart_unicode

from codename_bamboo.preference import IMAGE_TYPE
from codename_bamboo.preference import IMAGE_SIZE, THUMB_SIZE

def __get_people(username):
    """
    Return people object based on username
    """


def __make_uid(raw_name, raw_latitude, raw_longitude):
    """
    Return a sha1 hash based on username, location and current time
    """
    name = raw_name.encode('utf-8')
    latitude = raw_latitude.encode('utf-8')
    longitude = raw_longitude.encode('utf-8')
    timestamp = str(datetime.now()).replace(' ', '-').encode('utf-8')  

    message = hashlib.sha1(name+latitude+longitude+timestamp)

    return message.hexdigest()


def __make_tags_list(raw_tags):
    """
    Split raw tags string into list with white space
    """
    return smart_unicode(raw_tags).split(' ')


def __make_img_thumb(raw_file, uid):
    """
    Return opened image and thumb object
    """
    raw_image = Image.open(raw_file)
    raw_thumb = raw_image.copy()

    raw_image.thumbnail(IMAGE_SIZE, Image.ANTIALIAS)
    raw_thumb.thumbnail(THUMB_SIZE, Image.ANTIALIAS)

    image = '/tmp/' + uid + '.' + IMAGE_TYPE
    thumb = '/tmp/' + uid + '.thumb.' + IMAGE_TYPE

    raw_image.save(image, IMAGE_TYPE)
    raw_thumb.save(thumb, IMAGE_TYPE)

    return (open(image, 'r'), open(thumb, 'r'))


def __make_gridfs_images(raw_file, uid, username):
    """
    Store place image and thumb into mongodb's gridbs
    then return them for reference
    """
    id = str(uid) + str(username) + str(datetime.now()).replace(' ', '-')

    fs = GridFSStorage()
    raw_image = Image.open(raw_file)
    raw_thumb = raw_image.copy()

    raw_image.thumbnail(IMAGE_SIZE, Image.ANTIALIAS)
    raw_thumb.thumbnail(THUMB_SIZE, Image.ANTIALIAS)

    image = id + '.' + IMAGE_TYPE
    image_path = '/tmp/' + image
    thumb = id + '.thumb.' + IMAGE_TYPE
    thumb_path = '/tmp/' + thumb

    raw_image.save(image_path, IMAGE_TYPE)
    raw_thumb.save(thumb_path, IMAGE_TYPE)

    print(image_path)
    print(thumb_path)

    fs.save(image, open(image_path, 'r'))
    fs.save(thumb, open(thumb_path, 'r'))

    return (fs.open(image), fs.open(thumb))
